package com.sjme.interceptor;

import com.sjme.domain.user.User;
import com.sjme.threadLocal.UserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class InterviewInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断请求来源，若请求头X-Request-Source不为空，则说明是其他模块的远程调用
        String requestSource = request.getHeader("X-Request-Source");
        if (!StringUtils.isEmpty(requestSource)) {
            // 若请求头包含X-Request-Source，说明当前请求是其他模块发起的远程调用，
            // 可以判断是哪个模块的远程调用，从而进行一些特殊操作
        }
        // 设置用户信息到线程变量
        String userId = request.getHeader("userId");
        User user = new User();
        user.setId(userId);
        UserThreadLocalUtil.setUser(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求结束后，清除线程变量中的用户信息，防止读取脏数据
        log.info("==========请求结束，清除User数据=========");
        UserThreadLocalUtil.removeUser();
    }
}
